//
//  SwiftUIView.swift
//  
//
//  Created by Hoa.wang on 2021/10/19.
//

import SwiftUI

public struct HoaADBanner: View {
    
    public enum SourceType {
        case url(uri: String)
        case json(jsonString: String)
    }
    
    private var soruceType: SourceType
    
    @State private var models: [HoaAdModel] = []
    
    @State private var model: HoaAdModel!
    
    @State private var image: UIImage!
    
    public init(type: HoaADBanner.SourceType) {
        self.soruceType = type
    }
    
    public var body: some View {
        
        Button {
            if let url = model?.link, let uri = URL(string: url) {
                UIApplication.shared.open(uri, options: [:], completionHandler: nil)
            }
        } label: {
            if let image = image {
                Image(uiImage: image)
                    .resizable()
                    .frame(height: 80)
            }
            else {
                Color.gray
                    .frame(height: 80)
            }
        }
        .onAppear(perform: populateAds)
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
            self.model = self.models.randomElement()
            fetchImage()
        }
    }
    
    func populateAds() {
        
        switch soruceType {
        case .url(let uri):
            guard let urli = URL(string: uri) else {
                print("url is not support. error: \(uri)")
                return
            }
            Webservice().getAllAds(url: urli) { result in
                switch result {
                case .success(let ads):
                    DispatchQueue.main.async {
                        self.models = ads
                        self.model = ads.randomElement()
                        fetchImage()
                    }
                case .failure(let error):
                    print(error.localizedDescription)
                }
            }
        case .json(let jsonString):
            break
        }
    }
    
    func fetchImage() {
        
        guard let uri = model?.image, let url = URL(string: uri) else {
            return
        }
        
        Webservice().getImage(url: url) { result in
            switch result {
            case .success(let image):
                DispatchQueue.main.async {
                    self.image = image
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
        
    }
}

struct HoaADBanner_Previews: PreviewProvider {
    static var previews: some View {
        HoaADBanner(type: .url(uri: "https://ad.hoacode.com/app.json"))
    }
}
